package cn.itbaizhan.tyut.exam.sys.servlets;

import cn.itbaizhan.tyut.exam.model.Info;
import cn.itbaizhan.tyut.exam.model.InfoMgr;
import com.alibaba.fastjson.JSON;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author cengy
 */
public class InitServletContextListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        ServletContext servletContext = servletContextEvent.getServletContext();
        // 获取当前应用的真实路径
        String path = servletContext.getRealPath("/");
        Path filePath = Paths.get(path + "/info.json");
        String fileContent = null;
        try {
            fileContent = Files.lines(filePath).collect(Collectors.joining());
            List<Info> infoList = JSON.parseArray(fileContent, Info.class);
            InfoMgr.INSTANCE.infoList.addAll(infoList);

            InfoMgr.INSTANCE.infoList.forEach(info -> {
                info.after();
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }
}
